package controllers;

import form.Carpool.CreateCarpool;
import form.Carpool.JoinCarpool;
import gateway.CarpoolDB;
import gateway.DatabaseGateway;
import gateway.exception.CarpoolDBException;
import model.Carpool;
import play.data.Form;
import play.libs.Json;
import play.mvc.Controller;
import play.mvc.Result;
import session.SessionManager;
import util.HTMLUtil;

import java.sql.SQLException;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: Tom
 * Date: 17-2-14
 * Time: 15:44
 */
public class GroupActions extends Controller {

    public static Result createGroup(){
        System.out.println("creating a group...");

        CreateCarpool createCarpool = Form.form(CreateCarpool.class).bindFromRequest().get();

        CarpoolDB db = new CarpoolDB();
        try {
            db.createCarpoolGroup(createCarpool.getCarpool_name(), SessionManager.getEmail());
        } catch (CarpoolDBException e) {
            return ok(views.html.carpool.create_group.render("", HTMLUtil.p_error(e.getMessage())));
        } catch (SQLException e) {
            return ok(views.html.carpool.create_group.render("", HTMLUtil.p_error("An error occurred trying to join the group.")));
        }

        return redirect(routes.Application.index());
    }

    public static Result createGroupForm(){
        return ok(views.html.carpool.create_group.render("Create Carpool group", ""));
    }

    public static Result joinGroup(){
        JoinCarpool joinCarpool = Form.form(JoinCarpool.class).bindFromRequest().get();

        CarpoolDB db = new CarpoolDB();
        try {
            db.joinCarpoolGroup(SessionManager.getEmail(), joinCarpool.getGroup_id());
        } catch (CarpoolDBException e) {
            return ok(views.html.carpool.join_group.render("", HTMLUtil.p_error(e.getMessage())));
        } catch (SQLException e) {
            return ok(views.html.carpool.join_group.render("", HTMLUtil.p_error("An error occurred trying to join the group.")));
        }

        return ok(views.html.carpool.join_group.render("", HTMLUtil.p_success("Successfully joined Carpool group!")));
    }

    public static Result joinGroupForm(){
        return ok(views.html.carpool.join_group.render("Join Carpool group", ""));
    }


    public static Result updateGroupName(){
        return TODO;
    }


    public static Result leaveGroup(){

        return TODO;
    }


    public static Result groupOverview(){
        return ok(views.html.carpool.group_overview.render("", ""));
    }


    public static Result getCarpoolGroups(){
        CarpoolDB db = new CarpoolDB();
        try {
            return ok(Json.toJson(db.getJoinedCarpoolGroups(SessionManager.getEmail())));
        } catch (CarpoolDBException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return ok(Json.toJson("[]"));


    }


}
